/*
 * @ author madman 
 * @ use 客户列表
 */
const ClientModel = require('../../models/nexmo/client.model');
const CountryModel = require('../../models/nexmo/country.model');
const rentalModel = require('../../models/nexmo/rental.model');
const PriceModel = require('../../models/nexmo/price.model');
const topupModel = require('../../models/nexmo/topup.model');
const Utils = require('../utils');
const Nexmo = require('../utils/nexmo');
var shortid = require('shortid');
class Client {
    // 更新
    async update(ctx) {
        const _body = ctx.request.body
        let _params = Utils._params(_body)
        var options
        _params.updataAt = new Date()
        if (_params.appid === 'update'){
            _params.appid = shortid.generate()
        }
        if (_params.remainingMoney) {
            options = {
                remainingMoney: _params.remainingMoney
            }   
        }
        const result = await ClientModel.updateOne({ _id: _body._id }, { $set: _params.remainingMoney ? options: _params });
        if (result) {
            if (_params.remainingMoney) {
                var _options = {
                    msisdn: _params.msisdn,
                    dialingPrefix: _params.dialingPrefix,
                    countryName: _params.countryName,
                    price: _params.money
                }
                await topupModel.create(_options)
            }
            return ctx.success({ msg: '更新成功' });
        } else {
            return ctx.error({ msg: '更新失败' });
        }
    }
    // 获取客户号码的C端APPID
    async query(ctx) {
        const msisdn = ctx.query.msisdn
        const appid = ctx.query.appid
        let options = {}
        if (appid) {
            options.appid = appid
        }
        if (msisdn) {
            options.msisdn = msisdn
        }
        const result = await ClientModel.findOne(options, {_id: 0,msisdn: 1, appid:1, country:1, remainingMoney: 1, nextBillingDay: 1})
        .populate('country', {_id: 0, dialingPrefix:1, countryCode: 1});
        if (result) {
            return ctx.success({ msg: '查询成功', data: result});
        } else {
            return ctx.error({ msg: '查询失败' });
        }
    }
    // 获取客户列表
    async list(ctx) {
      const options = {
          name: 'nexmo/client',
          type: 'pop',
          findField: {},
          populate: 'country', 
          populateField: 'countryCode countryName monthPrice inPriceCost inPrice dialingPrefix'
      }
       
      if (ctx.query.msisdn) {
        options.findField.msisdn = new RegExp(ctx.query.msisdn, 'i')
      }
      if (ctx.query.remainingMoney) {
        options.findField.remainingMoney = {$lt: parseFloat(ctx.query.remainingMoney)}
      }
      if (ctx.query.nextBillingDateDay) {
        options.findField.nextBillingDay = {$lt: parseFloat(ctx.query.nextBillingDateDay)}
      }
      let data = await Utils.getPageList(ctx, options)
    // 判断本地是否有记录购买电话号码，如果没有记录从第三方获取
    //   if (data.result.length > 0) {
        return ctx.success({
            data: {
                total: data.total,
                pages: data.pages,
                result: data.result
            },
            msg: '查询成功'
        });
    //   } else {
        // var res =  await nexmo.numberList({ index: ctx.query.page, size:10})
        // const Country = await CountryModel.find({});
        // const Price = await PriceModel.find({});
        // const _number = res.numbers.map((item) => {
        //     Country.map((_item) => {
        //         if (item.country === _item.countryCode) {
        //             item.dialingPrefix = _item.dialingPrefix
        //         }
        //     })
        //     Price.map((priceitem) => {
        //         if (item.country === priceitem.countryCode) {
        //             item.country = priceitem._id
        //         }
        //     })
        //     item.nextBillingDate = Utils.currDateToDay(new Date(), Utils.currDateTo30());
        //     return item
        // })
        // var clientRes = await ClientModel.collection.insertMany(_number)
        // if (clientRes) {
        //     return ctx.success({
        //         data:{
        //             total: res.count,
        //             pages: Math.ceil(res.count / 10),
        //             result: _number
        //         }    
        //     });
        // } else {
        //     return ctx.error({ msg: '数据写入失败' });
        // }
    //   }
    }
}

export default new Client;